package test.nettyrpc.netty;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.lang3.reflect.MethodUtils;
import test.nettyrpc.model.MessageRequest;
import test.nettyrpc.model.MessageResponse;

import java.util.Map;

public class MessageRecvHandler extends ChannelInboundHandlerAdapter {

    private Map<String, Object> handleMap;

    public MessageRecvHandler(Map<String, Object> handleMap) {
        this.handleMap = handleMap;
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageResponse messageResponse = new MessageResponse();
        MessageRequest request = (MessageRequest) msg;
        String className = request.getClassName();
        Object serviceBean = handleMap.get(className);
        String methodName = request.getMethodName();
        Object[] parameters = request.getParamtersVal();
        try {
            messageResponse.setMessageId(request.getMessageId());
            Object obj = MethodUtils.invokeMethod(serviceBean, methodName, parameters);
            messageResponse.setResult(true);
            messageResponse.setResultObj(obj);
        } catch (Exception e) {
            messageResponse.setResult(false);
            messageResponse.setErrorMessage(e.getMessage());
            e.printStackTrace();
        }
        Channel channel = ctx.channel();
        channel.writeAndFlush(messageResponse);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //网络有异常要关闭通道
        ctx.close();
    }
}
